package com.ronsai.umtrack.api;

import android.content.Intent;

import com.ronsai.umtrack.MyApp;
import com.ronsai.umtrack.activity.LoginActivity;
import com.ronsai.umtrack.api.proxy.ProxyHandler;
import com.ronsai.umtrack.base.BaseApi;
import com.ronsai.umtrack.entity.Login;
import com.ronsai.umtrack.util.SPUtils;
import com.ronsai.umtrack.util.ToastUtil;

import java.lang.reflect.Proxy;

public class Api {

    // 域名
    public static final String BASE_URL = "http://he.ronsai.com";

    private volatile static ApiService apiService;

    private Api() {
        BaseApi baseApi = new BaseApi();
        ApiService service = baseApi.getRetrofit(BASE_URL).create(ApiService.class);
        apiService = (ApiService) Proxy.newProxyInstance(ApiService.class.getClassLoader(), new Class<?>[]{ApiService.class}, new ProxyHandler(service, new IGlobalManager() {
            @Override
            public void logout() {
                Intent intent = new Intent(MyApp.getContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApp.getContext().startActivity(intent);
                ToastUtil.showShortToast("登录信息已过期，请重新登录!");
            }

            @Override
            public void refreshToken(Login login) {
                if (login != null) {
                    SPUtils.getInstance().put("token", login.getToken());
                    SPUtils.getInstance().put("refreshToken", login.getRefreshToken());
                    MyApp.setToken(login.getToken());
                }
            }
        }));
    }

    public static ApiService getApiService() {
        if (apiService == null) {
            synchronized (Api.class) {
                if (apiService == null) {
                    new Api();
                }
            }
        }
        return apiService;
    }

}
